package org.example.weather.bigscreen.core.component;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.example.weather.bigscreen.core.repository.StWeatherUploadMapper;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
@Component
public class RefreshTableCacheApplicationRunner implements ApplicationRunner {
    @Value("${spring.shardingsphere.datasource.names}")
    private Set<String> names;

    @Value("${shardingsphere.datasource.tables.cache-key-prefix:%s_%s_cache_set}")
    private String dataSourceTablesCacheKey;

    private RedissonClient redissonClient;
    private Map<String, SqlSessionFactory> sqlSessionFactoryMap;

    public RefreshTableCacheApplicationRunner(final RedissonClient redissonClient, @Qualifier("sqlSessionFactoryMap") final Map<String, SqlSessionFactory> sqlSessionFactoryMap) {
        this.redissonClient = redissonClient;
        this.sqlSessionFactoryMap = sqlSessionFactoryMap;
    }

    @Override
    public void run(final ApplicationArguments args) throws Exception {
        for (final String name : names) {
            if (sqlSessionFactoryMap.containsKey(name)) {
                SqlSessionFactory sqlSessionFactory = sqlSessionFactoryMap.get(name);
                SqlSession sqlSession = sqlSessionFactory.openSession();
                StWeatherUploadMapper weatherUploadMapper = sqlSession.getMapper(StWeatherUploadMapper.class);
                List<String> showAllTablesLike = weatherUploadMapper.showAllTablesLike(name);
                RSet<String> set = redissonClient.getSet(String.format(dataSourceTablesCacheKey, name, weatherUploadMapper.getClass().getSimpleName()));
                showAllTablesLike.forEach(tableName -> log.info("cache load {} : {}", name, tableName));
                set.addAll(showAllTablesLike);
            }
        }
    }
}
